package com.weiya.commons.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Created by chuanqi on 2017/8/8.
 */
public class XStreamXmlUtils {

    public static String beanToXml(Object object) {
        XStream xStream = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("__", "_")));
        xStream.autodetectAnnotations(true);
        xStream.processAnnotations(object.getClass());
        return xStream.toXML(object).replace(" ", "");
    }

    public static Map<String, String> xmlToMap(String xmlStr)
            throws ParserConfigurationException, IOException, SAXException {
        StringReader sr = new StringReader(xmlStr);
        InputSource is = new InputSource(sr);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(is);
        // 获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, String> map = new HashMap<String, String>();
        int i = 0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if (node instanceof Element) {
                if (!StringUtils.isBlank(node.getTextContent())) {
                    map.put(node.getNodeName(), node.getTextContent());
                }
            }
            i++;
        }
        return map;
    }

    public static <T> T xmlToBean(String xml, Class<T> clazz) {
        XStream xStream = new XStream(new DomDriver());
        xStream.alias("xml", clazz);
        return (T) xStream.fromXML(xml);
    }
}
